﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace PickingGuide.Handle
{
    public class TcpClientHandler
    {
        private TcpClient tcpClient;
        private NetworkStream stream;
        public Action<string> OnReceiveData;

        public void Connect(string ip,int port)
        {
            try
            {
                tcpClient = new TcpClient();
                tcpClient.Connect(IPAddress.Parse(ip), port);
                stream = tcpClient.GetStream();
                new Task(() => MyReceiveData(tcpClient)).Start();
            }catch (Exception ex)
            {
                throw ex;
            }
        }

        private void MyReceiveData(TcpClient tcpClient)
        {
            byte[] data = new byte[1024];
            while (true)
            {
                int count = stream.Read(data, 0, 1024);
                String str = Encoding.Default.GetString(data, 0, count);
                OnReceiveData?.BeginInvoke(str,null,null);
            }

        }

        public void Send(string sendTxt)
        {
            String str = sendTxt;
            byte[] data = Encoding.Default.GetBytes(str);
            stream.Write(data, 0, data.Length);
        }
    }
}
